package com.yoomiito.app.ui.songduoduo;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.AppBarLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yoomiito.app.ImmersionBarFragment;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.BaseList;
import com.yoomiito.app.model.ViewType;
import com.yoomiito.app.model.sdd.SddFreeGoodsList;
import com.yoomiito.app.model.sdd.SddUserData;
import com.yoomiito.app.model.sdd.SddVipGoodsInfo;
import com.yoomiito.app.model.sdd.ShareMsg;
import com.yoomiito.app.utils.ColorUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.widget.SpacingDecoration;
import com.yoomiito.app.widget.dialog.ShareSendMoreAdDialog;
import com.yoomiito.app.widget.expand.ExpandView;
import com.yoomiito.app.widget.songduoduo.GiverInfoView;
import com.yoomiito.app.widget.songduoduo.SendMoreFreeGoodsZoneView;

import butterknife.BindView;

public class SendMoreActivity extends BaseActivity<SendMoreActPresenter> {

    @BindView(R.id.parentLayout)
    LinearLayout parentLayout;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.rcy)
    RecyclerView rcy;
    @BindView(R.id.toolbarLl)
    LinearLayout toolbarLl;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.sendGift)
    ImageView sendGift;
    @BindView(R.id.iv_back_left)
    ImageView back;
    @BindView(R.id.tv_center)
    TextView title;
    private SendMoreFreeGoodsZoneView freeGoodsZoneView;
    private SendMoreGoodsAdapter vipGoodsAdapter;
    private GiverInfoView giverListView;
    private ExpandView expandView;
    private int mCurrentPage = 1;

    public static void start(Context context){
        Intent intent = new Intent(context,SendMoreActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_send_more;
    }

    @Override
    public SendMoreActPresenter newP() {
        return new SendMoreActPresenter(App.mAppConfig);
    }

//    @Override
//    public void initImmersionBar() {
//        ImmersionBar.with(this).keyboardEnable(false).init();
//    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        title.setText("送多多");
        back.setOnClickListener(v -> finish());
        initHeadView();
        appBarLayout.addOnOffsetChangedListener((appBarLayout, i) -> {
            if (i == 0) {//展开
                toolbarLl.setBackgroundResource(R.color.color_tran);
                titleTv.setVisibility(View.INVISIBLE);
            }
            if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {//折叠
                toolbarLl.setBackground(ColorUtils.INSTANCE.gradient("#FFFF246C", "#FFFF035B", GradientDrawable.Orientation.LEFT_RIGHT));
                titleTv.setVisibility(View.VISIBLE);
            } else {//中间
                toolbarLl.setBackgroundResource(R.color.color_tran);
                titleTv.setVisibility(View.INVISIBLE);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshlayout -> {
            mCurrentPage++;
            getP().vipGoodsList(mCurrentPage);
        });
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshAllData();
        });
        sendGift.setOnClickListener(v -> {
            showLoading();
            getP().getSddShareMsg(5);
        });
    }


    private void initHeadView() {
        if (App.mAppConfig.getIsLogin() && Integer.valueOf(UserInfoConfig.getUser().getThree_role_id()) >= Type.LevelType.SDD_VIP_10) {
            giverListView = new GiverInfoView(context);
            LinearLayout.LayoutParams giverDataViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            parentLayout.addView(giverListView, giverDataViewLp);
            getP().sddUserInfo();
            sendGift.setVisibility(View.VISIBLE);
        } else {
            expandView = new ExpandView(context);
            LinearLayout.LayoutParams expandViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            parentLayout.addView(expandView, expandViewLp);
        }

        freeGoodsZoneView = new SendMoreFreeGoodsZoneView(context);
        LinearLayout.LayoutParams freeGoodsZoneViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        freeGoodsZoneViewLp.topMargin = DensityUtil.dp2px(15f);
        parentLayout.addView(freeGoodsZoneView, freeGoodsZoneViewLp);

        ImageView imageView = new ImageView(context);
        imageView.setImageResource(R.drawable.icon_lbzq);
        LinearLayout.LayoutParams imageViewLp = new LinearLayout.LayoutParams(DensityUtil.dp2px(151), DensityUtil.dp2px(22));
        imageViewLp.gravity = Gravity.CENTER_HORIZONTAL;
        imageViewLp.topMargin = DensityUtil.dp2px(16);
        imageViewLp.bottomMargin = DensityUtil.dp2px(11);
        parentLayout.addView(imageView, imageViewLp);

        GridLayoutManager gl = new GridLayoutManager(context, 2);
        gl.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {

            @Override
            public int getSpanSize(int i) {
                return vipGoodsAdapter.getData().get(i).getViewType() == SendMoreGoodsAdapter.BigImageType ? 2 : 1;
            }
        });
        rcy.setLayoutManager(gl);
        rcy.addItemDecoration(new SpacingDecoration(DensityUtil.dp2px(10), DensityUtil.dp2px(10), true));
        vipGoodsAdapter = new SendMoreGoodsAdapter(context, null);
        rcy.setAdapter(vipGoodsAdapter);


        getP().freeGoodsList();
        getP().vipGoodsList(mCurrentPage);
    }

    private void refreshAllData(){
        mCurrentPage=1;
        if (parentLayout.getChildAt(0) instanceof GiverInfoView){
            getP().sddUserInfo();
        }
        getP().freeGoodsList();
        getP().vipGoodsList(mCurrentPage);
    }

    /**
     *
     * @param isSwitch 是否强制转换为展示数据的view 非强制时，根据three_role_id>=Type.LevelType.SDD_VIP_10 {@link Type.LevelType}来判断
     */
    public void changVipHeader(boolean isSwitch) {
        boolean isLogin = App.mAppConfig.getIsLogin();
        View view0 = parentLayout.getChildAt(0);
        if (isLogin) {
            if (!(view0 instanceof GiverInfoView)) {
                if (isSwitch||Integer.valueOf(UserInfoConfig.getUser().getThree_role_id()) >= Type.LevelType.SDD_VIP_10) {
                    parentLayout.removeViewAt(0);
                    if (giverListView==null){
                        giverListView = new GiverInfoView(context);
                        LinearLayout.LayoutParams giverDataViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        parentLayout.addView(giverListView, 0, giverDataViewLp);
                    }else {
                        parentLayout.addView(giverListView, 0);
                    }
                    sendGift.setVisibility(View.VISIBLE);
                    getP().sddUserInfo();
                }
            }
        } else {
            if (!(view0 instanceof ExpandView)) {
                parentLayout.removeViewAt(0);
                if (expandView==null){
                    expandView = new ExpandView(context);
                    LinearLayout.LayoutParams expandViewLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    parentLayout.addView(expandView, 0, expandViewLp);
                }else {
                    parentLayout.addView(expandView, 0);
                }
                sendGift.setVisibility(View.GONE);
            }
        }

    }

    public void freeGoodsData(SddFreeGoodsList freeGoodsData) {
        freeGoodsZoneView.setGoodsData(freeGoodsData);
    }

    public void vipGoodsData(BaseList<ViewType<SddVipGoodsInfo>> datas) {
        if (datas.getCurrent_page() == 1) {
            vipGoodsAdapter.newData(datas.getData());
            smartRefreshLayout.finishRefresh(true);
            smartRefreshLayout.setNoMoreData(false);
        } else {
            vipGoodsAdapter.addData(datas.getData());
            smartRefreshLayout.finishLoadMore(true);
        }
        L.i("ss:  "+datas.getCurrent_page() +"         "+ datas.getLast_page());
        if (datas.getCurrent_page() == datas.getLast_page()) {
            smartRefreshLayout.finishLoadMoreWithNoMoreData();
        }
        mCurrentPage = datas.getCurrent_page();
    }


    public void sddShareMsg(ShareMsg shareMsg) {
        ShareSendMoreAdDialog dialog = new ShareSendMoreAdDialog(context, null, shareMsg, ShareSendMoreAdDialog.GoodsListType);
        dialog.setOnShowListener(v ->
                dismissLoading()
        );
        dialog.show();
    }

    public void vipUserData(SddUserData data) {
        giverListView.updateUserData(data);
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {//15219200089
        super.eventMessage(eventMessage);
        if (Type.EventMsgType.SDD_UPDATE_DATA.equals(eventMessage.getEventType())) {//送多多同意赠送礼品
            getP().sddUserInfo();
        }
        //送多多VIP购买成功 则强制刷新切换为送多多数据view
        L.i("sdd收到消息："+eventMessage.toString());
        if (Type.EventMsgType.BuyComplete.equals(eventMessage.getEventType())&&Type.GoodsType.GiveMore==eventMessage.getGoodsType()){//购买
            changVipHeader(true);
            getP().sddUserInfo();
            getP().freeGoodsList();
            mCurrentPage = 1;
            getP().vipGoodsList(mCurrentPage);
        }
        //登录 登出 需要刷新全部数据
        if (Type.EventMsgType.LoginOut.equals(eventMessage.getEventType())
                || Type.EventMsgType.LoginSuccess.equals(eventMessage.getEventType())){
            changVipHeader(false);
            getP().freeGoodsList();
            mCurrentPage = 1;
            getP().vipGoodsList(mCurrentPage);
        }
    }
}
